package com.hhhn.wk.main.tab4.allorder.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hhhn.wk.R;
import com.hhhn.wk.app.MyApplication;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.config.Config;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.SharePreferencesUser;
import com.hhhn.wk.utils.mi.AES;
import com.hhhn.wk.widget.select_img.SingleFileLimitInterceptor;
import com.hhhn.wk.widget.select_img.adapter.PickAdapter;
import com.hhhn.wk.widget.uploading_picture.Bimp;
import com.hhhn.wk.widget.uploading_picture.FileUtils;
import com.hhhn.wk.widget.uploading_picture.PhotoActivity;
import com.hhhn.wk.widget.uploading_picture.TestPicActivity;
import com.hhhn.wk.widget.MyGridView9;
import com.imnjh.imagepicker.SImagePicker;
import com.imnjh.imagepicker.activity.PhotoPickerActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/1/16 0016    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 发布评价
 * * * * * * * * * * * */
public class IssueEvaluateActivity extends BaseActivity{
    ArrayList<String> pathList=new ArrayList<>();
    private ImageView imageView;
    private GridView gridView;
    private PickAdapter pickAdapter;
    public static final String AVATAR_FILE_NAME = "avatar.png";
    public static final int REQUEST_CODE_AVATAR = 100;
    public static final int REQUEST_CODE_IMAGE = 101;
    private TextView tv_title;
    private RatingBar mRatingBar;
    private RatingBar mRatingBar2;
    private RatingBar mRatingBar3;
    private LinearLayout ll_issue;//发布
    String img = "";//商品图片
    String productId = "";//商品id
    String ordersCode = "";//订单编号
    String orderProId = "";//orderProId
    int serviceLevel=1;
    int serviceLevel2=1;
    int serviceLevel3=1;
    private EditText et_message;
    Intent intent;
    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_issue_evaluate);
         intent=getIntent();
         img = intent.getStringExtra("img");//商品图片
         productId = intent.getStringExtra("productId");//商品id
         ordersCode = intent.getStringExtra("ordersCode");//订单编号
         orderProId = intent.getStringExtra("orderProId");//orderProId
    }
    @Override
    protected void initView() {
        et_message=findViewById(R.id.et_message);
        ll_issue=findViewById(R.id.ll_issue);
        mRatingBar=findViewById(R.id.mRatingBar);
        mRatingBar2=findViewById(R.id.mRatingBar2);
        mRatingBar3=findViewById(R.id.mRatingBar3);
        tv_title=findViewById(R.id.tv_title);
        pickAdapter = new PickAdapter(IssueEvaluateActivity.this);
        gridView =  findViewById(R.id.image_grid);
        imageView =  findViewById(R.id.imageView);
        gridView.setAdapter(pickAdapter);
    }
    @Override
    protected void initData() {
        tv_title.setText("发表评价");
    }
    @Override
    protected void initClick() {
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SImagePicker
                        .from(IssueEvaluateActivity.this)
                        .maxCount(3)
                        .rowCount(3)
                        .setSelected(pathList)
                        .showCamera(true)
                        .pickMode(SImagePicker.MODE_IMAGE)
                        .fileInterceptor(new SingleFileLimitInterceptor())
                        .forResult(REQUEST_CODE_IMAGE);
            }
        });
        mRatingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                int j=(int)rating;
                switch (j){
                    case 1:
                        serviceLevel=1;
                        break;
                    case 2:
                        serviceLevel=2;
                        break;
                    case 3:
                        serviceLevel=3;
                        break;
                    case 4:
                        serviceLevel=4;
                        break;
                    case 5:
                        serviceLevel=5;
                        break;
                }
            }
        });
        mRatingBar2.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                int j=(int)rating;
                switch (j){
                    case 1:
                        serviceLevel2=1;
                        break;
                    case 2:
                        serviceLevel2=2;
                        break;
                    case 3:
                        serviceLevel2=3;
                        break;
                    case 4:
                        serviceLevel2=4;
                        break;
                    case 5:
                        serviceLevel2=5;
                        break;
                }
            }
        });
        mRatingBar3.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                int j=(int)rating;
                switch (j){
                    case 1:
                        serviceLevel3=1;
                        break;
                    case 2:
                        serviceLevel3=2;
                        break;
                    case 3:
                        serviceLevel3=3;
                        break;
                    case 4:
                        serviceLevel3=4;
                        break;
                    case 5:
                        serviceLevel3=5;
                        break;
                }
            }
        });
        ll_issue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = et_message.getText().toString().trim();
                if (trim==null||"".equals(trim)){
                    toastWk("评价不能为空");
                    return;
                }
                if (trim.length()<10){
                    toastWk("评价不能少于10个字");
                    return;
                }
                if (pathList.size()==0){
                    getRegister("");
                }else {
                    goOK1(pathList);
                }
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            pathList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
            final boolean original = data.getBooleanExtra(PhotoPickerActivity.EXTRA_RESULT_ORIGINAL, false);
            pickAdapter.setNewData(pathList);
            if (pathList.size()>2){
                imageView.setVisibility(View.GONE);
            }else {
                imageView.setVisibility(View.VISIBLE);
            }
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
    }
    /**
     * 提交1图片
     */
    private void goOK1(ArrayList<String> pathList) {
        showLoad();
        RequestParams params = new RequestParams(Constants.HTTPUPIMG);
        params.addHeader("Content-Type", "application/x-www-form-urlencoded");
        List<KeyValue> list = new ArrayList<>();
        //请求参数
        for (int i=0;i<pathList.size();i++){
            list.add(new KeyValue("file_data"+i, new File(pathList.get(i))));
            Log.d("111", "goOK1: "+pathList.get(i));
        }
        MultipartBody body = new MultipartBody(list, "UTF-8");
        params.setRequestBody(body);
        Log.d("图片", "params: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("提交1图片", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    int reason = jsonObject.getInt("code");
                    if (reason==0) {
                        String data = jsonObject.getString("data");
//                        String string="";
//                        if (data.length()<2){
//                            getRegister(data.get(0).toString());
//                        }else {
//                            for (int i=0;i<data.length();i++){
//                                string=string+","+data.get(i).toString();
//                            }
//                            String str=string.substring(1,string.length());
                            getRegister(data);
//                        }
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("提交1图片-第二个", ex + "");
                ex.printStackTrace();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("提交1图片-第三个", cex + "");
            }
            @Override
            public void onFinished() {
                Log.d("提交1图片-第四个", "onFinished");
            }
        });
    }
    /**
     * 提交2
     */
    private void getRegister(final String data) {
        RequestParams params = AllPublic.getParamsEvaluate(IssueEvaluateActivity.this, "/evaluatePro", false);
        params.addParameter("productId",productId );//商品ID
        params.addParameter("ordersCode",ordersCode );//订单编号
        params.addParameter("merchantId", getUser().getUid());//商户ID
        params.addParameter("evaluationImage",data );//评价图片地址
        params.addParameter("serviceLevel",serviceLevel );//服务水平评分
        params.addParameter("veryFast",serviceLevel2 );//物流速度评分
        params.addParameter("evaluationScore", serviceLevel3);//商品评分
        params.addParameter("evaluationContent", et_message.getText().toString().trim());//商品评价内容
        params.addParameter("orderProId",orderProId );//订单关联商品ID
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String decode) {
                Log.d("@", "onSuccess: "+decode);
                String result = AllPublic.jsonDesDecode(decode);//解密
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {//成功
                        toastWk("评价成功");

                        setResult(1,intent);

                        finish();
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismissLoad();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("提交-第二个", ex + "");
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("提交-第三个", cex + "");
                dismissLoad();
            }
            @Override
            public void onFinished() {
                Log.d("提交-第四个", "onFinished");
                dismissLoad();
            }
        });
    }
    public void myBR(String type) {
        Intent mIntent = new Intent(type);
        //发送广播
        sendBroadcast(mIntent);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
